//
//  UserCenterViewController.m
//  WorkNest
//
//  Created by Billy on 15/7/3.
//  Copyright (c) 2015年 nest. All rights reserved.
//
// if ([segue.identifier isEqualToString:@"jifen"]) {
//TaskViewController * task=segue.destinationViewController;
//task.hidesBottomBarWhenPushed=YES;
//}
//hidesBottomBarWhenPushed=YES;

// [self.navigationController setNavigationBarHidden:YES animated:YES];

#import "UserCenterViewController.h"
#import "HeaderView.h"
//#import "PersonMessageVC.h"
//#import "TransactionRecordsVC.h"
#import "SetMeViewController.h"
//#import "MyCollectionVC.h"
//#import "MyDevelopmentListVC.h"

#import "user_myProductViewController.h"
//#import "user_myRecommendViewController.h"
//#import "user_myPriceQueryViewController.h"
//#import "user_myAllProductViewController.h"
#import "PriceQueryTableViewController.h"
//#import "TransactionRecordViewController.h"
#import "UIAlertView+BlocksKit.h"
#import "PlatformStyleViewController.h"
#import "MyInfomationViewController.h"
#import "LargeGoodsViewController.h"
#import "UserInfoModel.h"
#import "LoginViewController.h"
#import "UserInfoViewController.h"
#import "RecommendViewController.h"
#import "WaittingPayViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDK/ShareSDK+Base.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetCustomItem.h>

@interface UserCenterViewController ()<enterSetCenterDelegate, UIAlertViewDelegate>

@property (nonatomic,strong) HeaderView *headerView;
@property (nonatomic, strong) UserInfoModel *infoModel;

@end

@implementation UserCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    // 视图创建
    [self createSubview];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInfoCount) name:@"tuisong" object:nil];
}

- (void)updateInfoCount {
    [self navigationRightItem];
}

  //隐藏导航栏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)requestData {
    if (![UserModel sharedInstance].userName) {
        [self.navigationController pushViewController:[LoginViewController new] animated:YES];
        return;
    }
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData getUserDetail:[UIUtil toJsonString:dic] withBlock:^(UserInfoModel *model, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.infoModel = model;
            self.headerView.userInfo = _infoModel;
        }
    }];
}

#pragma  mark 创建头部 中部 视图
- (void)createSubview {
    //添加头部视图
    self.headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , SCREEN_WIDTH/320*184)];
    [self.view addSubview:self.headerView];
    self.headerView.delegate = self;
//    self.headerView.backgroundColor = [UIColor redColor];
    
    //UICollectionView
    //确定是水平滚动，还是垂直滚动
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.headerView.frame.size.height + self.headerView.frame.origin.y, SCREEN_WIDTH, 194) collectionViewLayout:flowLayout];
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    [self.collectionView setBackgroundColor:[UIColor whiteColor]];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.scrollEnabled = NO;
    //注册Cell，必须要有
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];

    [self.view addSubview:self.collectionView];
    [self navigationRightItem];
}

- (void)navigationRightItem {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - 50, 20, 40, 30);
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"infomation"]];
    imageView.frame=CGRectMake(15, 7, 18, 17);
    [button addSubview:imageView];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(27, 1, 13, 13)];
    label.text = [NSString stringWithFormat:@"%ld",[[UIApplication sharedApplication]applicationIconBadgeNumber]];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:10];
    label.backgroundColor = [UIUtil colorWithHexString:@"#F32E14"];
    label.layer.cornerRadius = 6.5;
    label.layer.borderWidth = 1;
    label.layer.masksToBounds = YES;
    label.layer.borderColor = [[UIUtil colorWithHexString:@"#F32E14"] CGColor];
    [button addSubview:label];
    [button addTarget:self action:@selector(gotoInfo) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:button];
    label.hidden = [label.text isEqualToString:@"0"]?YES:NO;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)gotoInfo {
    MyInfomationViewController *view = [[MyInfomationViewController alloc] init];
    [view setHidesBottomBarWhenPushed:YES];
    [self.navigationController.navigationBar setHidden:NO];
    [self.navigationController pushViewController:view animated:YES];
}

- (UILabel *)shareInfo:(UICollectionViewCell *)cell {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((cell.frame.size.width-27)/2 + 15, 8, 15, 15)];
    label.text = @"10";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:10];
    label.backgroundColor = [UIUtil colorWithHexString:@"#F32E14"];
    label.layer.cornerRadius = 7.5;
    label.layer.borderWidth = 1;
    label.layer.masksToBounds = YES;
    label.layer.borderColor = [[UIUtil colorWithHexString:@"#F32E14"] CGColor];
    return label;
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 10;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];
    NSArray *imageArray = @[@"me-Product",@"me-recommentstyle",@"me-Inquirysheet",@"me-Developmentsheet",@"me-Largeorders",@"me-collection",@"me-friends",@"me-Customerservice",@"me-set",@"me-exchange"];
    UIImageView *imageViewCell = [[UIImageView alloc] initWithFrame:CGRectMake((cell.frame.size.width-27)*1.0/2, 10, 27,27)];
    imageViewCell.contentMode = UIViewContentModeScaleAspectFit;
    imageViewCell.image = [UIImage imageNamed:imageArray[indexPath.row]];
    
    NSArray *titleArray = @[@"我的产品",@"我的推款",@"我的询价单",@"我的制版打样单",@"我的大货单",@"我的收藏",@"邀请好友",@"客 服",@"设 置",@"待支付"];
    UILabel *labelText = [[UILabel alloc] initWithFrame:CGRectMake(0, imageViewCell.frame.size.height+10, cell.contentView.bounds.size.width, 25)];
    labelText.textColor = [UIColor colorWithRed:130/255.0 green:130/255.0 blue:130/255.0 alpha:1];
    labelText.font = [UIFont systemFontOfSize:10];
    labelText.text = titleArray[indexPath.row];
    labelText.numberOfLines = 0;
    labelText.textAlignment = NSTextAlignmentCenter;
    
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    [cell.contentView addSubview:imageViewCell];
    [cell.contentView addSubview:labelText];
//    if (indexPath.item == 2 || indexPath.item == 3) {
//        [cell.contentView addSubview:[self shareInfo:cell]];
//    }
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCREEN_WIDTH/320*50, 67);
}


//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(15, 10, 15, 10);
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0) {
        user_myProductViewController *myProductVC = [[user_myProductViewController alloc]init];
        [myProductVC setHidesBottomBarWhenPushed:YES];
                [self.navigationController.navigationBar setHidden:NO];
        [self.navigationController pushViewController:myProductVC animated:YES];
    }
   if (indexPath.item == 1){
        RecommendViewController *myRecommendVC = [[RecommendViewController alloc]init];
        [myRecommendVC setHidesBottomBarWhenPushed:YES];
                [self.navigationController.navigationBar setHidden:NO];
        [self.navigationController pushViewController:myRecommendVC animated:YES];
    }
   if(indexPath.item == 2){
        PriceQueryTableViewController *myPriceQueryVC = [[PriceQueryTableViewController alloc]init];
       myPriceQueryVC.ifPriceQuery = YES;
        [myPriceQueryVC setHidesBottomBarWhenPushed:YES];
       [self.navigationController.navigationBar setHidden:NO];
        [self.navigationController pushViewController:myPriceQueryVC animated:YES];
        
    }
    if (indexPath.item == 3) {
        PriceQueryTableViewController *transactionVC = [[PriceQueryTableViewController alloc] init];
        transactionVC.ifPriceQuery = NO;
        [self.navigationController.navigationBar setHidden:NO];
        [transactionVC setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:transactionVC animated:YES];
    }
    if (indexPath.item == 4) {
        LargeGoodsViewController *myAllProductVC = [[LargeGoodsViewController alloc]init];
        [myAllProductVC setHidesBottomBarWhenPushed:YES];
          [self.navigationController.navigationBar setHidden:NO];
        [self.navigationController pushViewController:myAllProductVC animated:YES];
    }
    if (indexPath.item == 5) {
        PlatformStyleViewController *myCollection = [[PlatformStyleViewController alloc] init];
        [self.navigationController.navigationBar setHidden:NO];
        myCollection.titleName = @"我的收藏";
        myCollection.ifCategory = NO;
        [myCollection setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:myCollection animated:YES];

    }
    if (indexPath.item == 6) {
        UICollectionViewCell *cell = [[UICollectionViewCell alloc] init];
        [self requestShareContent:cell];
    }
    if (indexPath.item == 7) {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://0579-82388980"]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"0571-86700832" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
    if (indexPath.item == 8) {
    SetMeViewController *setMeVC = [[SetMeViewController alloc] init];
    [self.navigationController.navigationBar setHidden:NO];
    [setMeVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:setMeVC animated:YES];
    }
    if (indexPath.item==9) {
        WaittingPayViewController *transactionVC = [[WaittingPayViewController alloc] init];
        [self.navigationController.navigationBar setHidden:NO];
        [transactionVC setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:transactionVC animated:YES];
    }
}

- (void)requestShareContent:(UIView *)view {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData getSendMessage:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"获取推广内容失败":msg dismissBlock:nil];
            }
        } else {
            [self showShareActionSheet:view content:msg];
        }
    }];

}

- (void)showShareActionSheet:(UIView *)view content:(NSString *)content {
    /**
     * 在简单分享中，只要设置共有分享参数即可分享到任意的社交平台
     **/
    __weak UserCenterViewController *theController = self;
    
    //1、创建分享参数（必要）
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    NSArray* imageArray = @[[UIImage imageNamed:@"icon.png"]];
    [shareParams SSDKSetupShareParamsByText:content
                                     images:imageArray
                                        url:[NSURL URLWithString:@"http://pre.im/gckj"]
                                      title:@"衣单通APP应用邀请"
                                       type:SSDKContentTypeAuto];
    //2、分享
    [ShareSDK showShareActionSheet:view
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
//                           [theController showLoadingView:YES];
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else if(platformType == SSDKPlatformTypeMail && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、邮件应用没有设置帐号；2、设备不支持邮件应用；"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       default:
                           break;
                   }
                   if (state != SSDKResponseStateBegin)
                   {
//                       [theController showLoadingView:NO];
                       [theController.collectionView reloadData];
                   }
               }];
    
    //另附：设置跳过分享编辑页面，直接分享的平台。
    //        SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:view
    //                                                                         items:nil
    //                                                                   shareParams:shareParams
    //                                                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
    //                                                           }];
    //
    //        //删除和添加平台示例
    //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
    //        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
}

#pragma  mark 跳转到联系客服
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://0571-86700832"]];
    }
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark enterSetCenterDelegate 进入个人信息
- (void)enterSetCenter {
    UserInfoViewController *personMeView = [[UserInfoViewController alloc] init];
    personMeView.infoModel = _infoModel;
    [personMeView setHidesBottomBarWhenPushed:YES];
    personMeView.headBlock = ^(UIImage *image, NSString *nickName) {
        _infoModel.nickName = nickName;
        self.headerView.userInfo = _infoModel;
        self.headerView.image = image;
    };
    [self.navigationController.navigationBar setHidden:NO];
    [self.navigationController pushViewController:personMeView animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
